package com.zsd.android.webrtcdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.zsd.android.webrtcdemo.interfaces.IViewCallback;
import com.zsd.android.webrtcdemo.utils.ScreenUtil;

import org.webrtc.EglBase;
import org.webrtc.MediaStream;
import org.webrtc.RendererCommon;
import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoTrack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ChatRoomActivity extends AppCompatActivity implements IViewCallback {

    private FrameLayout videoLayout;

    private WebRTCManager webRTCManager;
    private EglBase rootEglBase;
    private VideoTrack localVideoTrack;
    private HashMap<String, SurfaceViewRenderer> videoViews;
    private ArrayList<String> userIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_room);
        initView();
    }

    private void initView() {
        videoViews = new HashMap<>();
        userIds = new ArrayList<>();
        rootEglBase = EglBase.create();
        videoLayout = findViewById(R.id.chat_room_video_layout);
        webRTCManager = WebRTCManager.getInstance();
        webRTCManager.setCallback(this);
        webRTCManager.joinRoom(this, rootEglBase);
    }

    /**
     *
     * @param stream 本地流，可以取到音频流和视频流数据
     * @param socketId 自己的id，服务器返回
     */
    @Override
    public void onSetLocalStream(MediaStream stream, String socketId) {
        List<VideoTrack> videoTracks = stream.videoTracks;
        if (videoTracks.size() > 0) {
            localVideoTrack = videoTracks.get(0);
        }
        addView(stream, socketId);
    }

    @Override
    public void onAddRemoteStream(MediaStream stream, String socketId) {
        addView(stream, socketId);
    }

    @Override
    public void onCloseWithId(String id) {
        removeView(id);
    }

    /**
     *
     * @param mediaStream 视频流（本地流或则远端的视频流）
     * @param userId 用户Id
     */
    private void addView(MediaStream mediaStream, String userId) {
        //不用系统的SurfaceView，而是用WebRtc给我们提供的
        SurfaceViewRenderer renderer = new SurfaceViewRenderer(this);
        //初始化SurfaceView
        renderer.init(rootEglBase.getEglBaseContext(), null);
        //设置缩放模式 按照View的宽度和高度设置
        //SCALE_ASPECT_FIT 按照摄像头预览的画面大小设置
        renderer.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        //翻转
        renderer.setMirror(true);
        //将摄像头的数据渲染到SurfaceViewRenderer
        if (mediaStream.videoTracks.size() > 0) {
            mediaStream.videoTracks.get(0).addSink(renderer);
        }
        videoViews.put(userId, renderer);
        userIds.add(userId);
        //将SurfaceViewRenderer添加到FrameLayout中
        //这时候的width = 0， height = 0
        videoLayout.addView(renderer);
        //指定宽度和高度
        int size = videoViews.size();
        for (int i = 0; i < size; i++) {
            String peerId = userIds.get(i);
            SurfaceViewRenderer viewRenderer = videoViews.get(peerId);
            if (viewRenderer != null) {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                layoutParams.height = ScreenUtil.getWidth(this, size);
                layoutParams.width = layoutParams.height;
                layoutParams.leftMargin = ScreenUtil.getX(this, size, i);
                layoutParams.topMargin = ScreenUtil.getY(this, size, i);
                viewRenderer.setLayoutParams(layoutParams);
            }
        }
    }

    /**
     * 移除View
     * @param id
     */
    private void removeView(String id) {
        SurfaceViewRenderer viewRenderer = videoViews.get(id);
        if (viewRenderer != null) {
            viewRenderer.release();
            videoViews.remove(id);
            userIds.remove(id);
            videoLayout.removeView(viewRenderer);

            //刷新布局
            int size = videoViews.size();
            for (int i = 0; i < size; i++) {
                String peerId = userIds.get(i);
                SurfaceViewRenderer renderer = videoViews.get(peerId);
                if (renderer != null) {
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                    layoutParams.height = ScreenUtil.getWidth(this, size);
                    layoutParams.width = layoutParams.height;
                    layoutParams.leftMargin = ScreenUtil.getX(this, size, i);
                    layoutParams.topMargin = ScreenUtil.getY(this, size, i);
                    renderer.setLayoutParams(layoutParams);
                }
            }
        }
    }

    public void toggleMic(boolean enableMic) {
        webRTCManager.toggleMic(enableMic);
    }

    public void toggleLager(boolean enableSpeaker) {
        webRTCManager.toggleLager(enableSpeaker);
    }

    public void toggleOpenCamera(boolean enableCamera) {
        webRTCManager.toggleOpenCamera(enableCamera);
    }

    public void toggleCamera() {
        webRTCManager.toggleCamera();
    }

    public void handUp() {
        exit();
        finish();
    }

    private void exit() {
        webRTCManager.exitRoom();
    }
}
